<?php
define('permission_allow', 'allow');
define('permission_deny', 'deny');

/*
 * 管理Module的Action
 * 需登录，登录Customer必须为0
 */

class ModuleAction extends Action
{
    /*
     * 显示当前/指定客户所有支持的Module
     * 需登录
     */
    public function index($cid = NULL, $order = "customerId", $orderBy = "desc", $start = 0, $limit = 25)
    {
        $CModule = D("customer_module_group");

        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $customerId = Session::$user["customerId"];

        // 如果不是管理员且查询其他客户插件，则不能查询，只返回自己的插件列表，没设置则查询自己的插件列表
        if ($customerId != 0 || !isset($cid)) {
            $cid = $customerId;
        }

        $where['customer.customerId'] = $cid;
        $where['customer.permission'] = permission_allow;
        if ($limit != -1) {
            /**
             * 20170713 - 修改底层customer多账号支持是备注
             * 全局搜索单独的customer相关('customer'/"customer"/wx_customer )搜出此处, 可是这里却是一个与此无关的alias, 所以这里不修改
             * LLyeap_wx_customer修改
             */
            $result = $CModule->alias("customer")->where($where)->join("wx_module_group gp ON customer.group = gp.group")
                ->field("gp.id, gp.name, gp.group, gp.description, gp.iconurl, customer.permission")
                ->order("$order $orderBy")->limit("$start,$limit")->select();
        } else {
            $result = $CModule->alias("customer")->where($where)->join("wx_module_group gp ON customer.group = gp.group")
                ->field("gp.id, gp.name, gp.group, gp.description, gp.iconurl, customer.permission")
                ->order("$order $orderBy")->select();
        }
// 		echo $CModule->getLastSql();
        $count = $CModule->where("customerId=$cid")->count();
        if (!isset($result)) {
            Output::instance()->resultCode(code_success, "未找到模块");
            return;
        }
        Output::instance()->objArray($result, $count);
    }

    /*
     * 显示当前/指定客户所有支持的Module,不分页
    * 需登录
    */
    public function getAll($cid = NULL, $order = "customerId", $orderBy = "desc")
    {
        $this->index($cid, $order, "desc", 0, -1);
    }

    /*
     * 获取客户所有的Module，支持的和不支持的都返回
     */
    public function getAllModuleGroup($cid, $order = "id", $orderBy = "desc", $start = 0, $limit = 25)
    {
        $CModule = D("module_group");

        $retVal = Session::init();
        if (!$retVal || !Session::isAdmin()) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $where["gp.display"] = 1;
        $result = $CModule->alias("gp")->where($where)
            ->join("wx_customer_module_group customer ON customer.group = gp.group and customer.customerId=$cid")
            ->field("gp.id, gp.name, gp.group, gp.description, gp.iconurl, customer.permission")
            ->order("$order $orderBy")->limit("$start, $limit")->select();
// 		Log::write($CModule->getLastSql());

        $count = $CModule->where($where)->count();

        if (!isset($result)) {
            Output::instance()->resultCode(code_success, "未找到模块");
            return;
        }
        Output::instance()->objArray($result, $count);
    }

    /**
     * 获取客户所有的Module分组，支持的和不支持的都返回
     *
     * @param        $cid
     * @param string $order
     * @param string $orderBy
     * @param int $start
     * @param int $limit
     * @param string $backend 后台版本:目前是mp/nmp
     * @modify lilei<LL_strive@163.com> 2017-05-16
     * 20170609 - 由于新版后台结构问题, 没有二层子页面, 所以这个接口虚设, 并无调用, 具体看接口getAllModuleByGroupUsage
     */
    public function getAllModuleGroupUsage($cid, $order = "id", $orderBy = "asc", $start = 0, $limit = 25, $backend = 'mp')
    {
        /** 1. 实例化数据模型 */
        $CModule = D("module_group");

        /** 2. 首先需要操作用户登录 */
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /** 3. 进入数据查询 */
		// 3.1 如果当前登陆者是平台管理员或者平台运营管理员则可以进行操作
		$agent = Session::$user['agent'];
        if (Session::isAdmin() || "operate" == $agent) {    // 用户拥有超管权限

            $arr_backend = [    // 后台版本数组
                'mp' => 'mp',
                'nmp' => 'nmp'
            ];

            /** 3.2 对各个版本数据进行组织, 核心内容 */
            if ($backend == 'mp') {
                /** 3.2.1 mp版后台 */

                /** 3.2.1.1 查询模块分组信息 */
                // 筛选条件
                $where['backend'] = $arr_backend[$backend];        // 筛选该版本的内容
                $where["display"] = 1;                             // 有效的
                $where["groupUsage"] = array("neq", '平台管理');    // 非平台管理的(2014-13-3平台管理员不显示)

                // mp版后台, 按照groupUsage分模块
                $result = $CModule
                    ->where($where)
                    ->group("groupUsage")
                    ->field("groupUsage")
                    ->order("$order $orderBy")
                    ->limit("$start, $limit")
                    ->select();

                if (!isset($result)) {  // 没有任何模块信息
                    Output::instance()->resultCode(code_success, "未找到模块");
                    return;
                }

                /** 3.2.1.2 查询模块分组, 组织数据 */
                $where["groupUsage"] = array("neq", null);;
                $count = $CModule->where($where)->group("groupUsage")->count();

                // 根据模块组, 将各模块下的有效数据组织起来
                for ($i = 0; $i < count($result); $i++) {
                    $condition["groupUsage"] = $result[$i]["groupUsage"];
                    $condition["display"] = 1;
                    $condition['backend'] = $arr_backend[$backend];

                    $modules = $CModule->where($condition)->order("$order $orderBy")->getField("name", true);
                    if ($modules) {
                        $result[$i]["groupDetail"] = implode(",", $modules);
                    }
                }

                /** 3.2.1.3 返回数据 */
                Output::instance()->objArray($result, $count);

            } else if ($backend == 'nmp') {
                /** 3.2.2 nmp版后台 */
                /** 3.2.2.1 查询一级导航栏目 */
                // 筛选条件
                $where = [
                    'backend' => $arr_backend[$backend],
                    'display' => 1,
                    'pid' => 0
                ];
                $firstLevelModules = $CModule
                    ->where($where)
                    ->order("$order $orderBy")
                    ->field('id, name, group, description, iconurl, modules, groupUsage, href, pid')
                    ->select();

                /** 3.2.2.2 查询二级导航栏目 */
                // 这里传false是因为需要把所有的module都返回, 所以不鉴权
                $firstLevelModules = $this->getSecondLevels($firstLevelModules, $order, $orderBy, FALSE);

                /** 3.2.2.3 组织数据返回 */
                $result = [
                    'total_data' => count($firstLevelModules),
                    'data' => $firstLevelModules ? $firstLevelModules : []
                ];

                Output::instance()->object($result);
            }

        } else {    // 用户无超管权限
            Output::instance()->resultCode(code_access_denied);
            return;
        }

    }

    /**
     * 获取客户所有的Module，支持的和不支持的都返回
     *
     * @param        $cid           哪个用户
     * @param null $groupUsage mp版本根据groupUsage来分模块查找的(nmp废弃不用, 返回所有, 不分组)
     * @param string $order
     * @param string $orderBy
     * @param int $start
     * @param int $limit
     * @param string $backend 后台的版本号, 默认为'mp'版
     */
    public function getAllModuleByGroupUsage($cid, $groupUsage = null, $order = "id", $orderBy = "desc", $start = 0, $limit = 25, $backend = 'mp')
    {
        $CModule = D("module_group");

        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        //如果当前登陆者是平台管理员或者平台运营管理员则可以进行操作
        $agent = Session::$user['agent'];
        if (Session::isAdmin() || "operate" == $agent) {
            $where["gp.display"] = 1;
            $where["gp.backend"] = $backend;    // 各版本的数据区分
            if ($backend == 'mp') { // 如果是mp版, 则需要根据groupUsage进行分别查询
                $where["gp.groupUsage"] = $groupUsage;
                $result = $CModule
                    ->alias("gp")
                    ->where($where)
                    ->join("wx_customer_module_group customer ON customer.group = gp.group and customer.customerId=$cid")
                    ->field("gp.id, gp.name, gp.group, gp.description, gp.iconurl, customer.permission")
                    ->order("$order $orderBy")
                    ->limit("$start, $limit")
                    ->select();

                // 总数
                $count = $CModule->alias("gp")->where($where)->count();

            } elseif ($backend == 'nmp') {  // nmp版, 不需要分页

                /**
                 * 由于新版后台结构问题, 不在进行二次页面, 也就少调用一层接口(getAllModuleGroupUsage)
                 *
                 * 1. 先查询所有一级导航module(超管导航除外)
                 * 2. 查询各一级下的所有二级导航module
                 * 3. 如果存在二级, 则把一级抛弃
                 * -. 一二级查询时, 都与wx_customer_module_group做链接鉴权
                 * -. 如果存在二级, 则二级的模块名(pname)为一级的名称, 如果不存在二级即只有一级本身, 则其模块名为''
                 */

                $where["gp.pid"] = 0;   // 所有一级导航

                // 查询所有一级导航module
                $first_result = $CModule
                    ->alias("gp")
                    ->where($where)
                    ->join("left join wx_customer_module_group customer ON customer.group = gp.group and customer.customerId=$cid")
                    ->field("gp.id, gp.name, gp.group, gp.description, gp.iconurl, customer.permission")
                    ->order("$order $orderBy")
                    ->select();

                $result = [];   // 这个result里用户放置module集
                // 遍历一级导航module, 处理其子级(二级)
                foreach ($first_result as $first_index => $first) {
                    $where["gp.pid"] = $first['id'];    // 子级别

                    // 查询各一级导航module下的二级导航module
                    $second_result = $CModule
                        ->alias("gp")
                        ->where($where)
                        ->join("left join wx_customer_module_group customer ON customer.group = gp.group and customer.customerId=$cid")
                        ->field("gp.id, gp.name, gp.group, gp.description, gp.iconurl, customer.permission")
                        ->order("$order $orderBy")
                        ->select();

                    if (!empty($second_result)) {   // 如果存在二级导航module

                        // 遍历处理二级对象内容
                        foreach ($second_result as $second_index => $second) {
                            $second_result[$second_index]['pname'] = $first['name'];    // 设置二级导航module的pname为一级的name
                            array_push($result, $second_result[$second_index]);         // 并且将二级里的一个一个对象内容追加到result里, 后面不在对一级的做处理, 即抛弃了一级
                        }
                    } else {    // 如果不存在二级
                        $first_result[$first_index]['pname'] = '';         // 设置一级本身的pname为''
                        array_push($result, $first_result[$first_index]);   // 同时将一级本身追加到result里
                    }
                }
                $count = count($result);
            }


            if (!isset($result)) {
                Output::instance()->resultCode(code_success, "未找到模块");
                return;
            }
            Output::instance()->objArray($result, $count);
        } else {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
    }
	
	/*
	 * 激活指定用户的插件
	 */
	public function activate($cid, $group) {
		$retVal = Session::init();
		if (!retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		//如果当前登陆者是平台管理员或者平台运营管理员则可以进行操作
		$agent = Session::$user['agent'];
	    if(Session::isAdmin()||"operate"==$agent){
			Session::switchCustomer(0);
			
			$GModule = D("module_group");
			$where["group"] = $group;
			$moduleGroup = $GModule->where($where)->find();
			if (!$moduleGroup) {
				Output::instance()->resultCode(code_custom_error);
				return;
			}
			
			$CModule = D("customer_module_group");
			$condition["customerId"] = $cid;
			$condition["group"] = $group;
			$customerGroup = $CModule->where($condition)->select();
			if (!$customerGroup) {
				$CModule->create();
				$CModule->customerId = $cid;
				$CModule->group = $group;
				$CModule->permission = permission_allow;
				$result = $CModule->add();
			} else {
				$result = $CModule->where($condition)->setField('permission', permission_allow);
			}
			
			if (!$result) {
				Log::write($CModule->getLastSql());
				Output::instance()->resultCode(code_sql_error);
				return;
			}

            // 调用模板消息接口, 配置该模块所使用到的模板消息
            $result = R('TemplateMessage/configModuleTemplate', [$group, $cid]);

            Session::switchCustomer($cid);
            $modules = $moduleGroup["modules"];
            $moduleArray = explode(",", $modules);
            foreach ($moduleArray as $module) {
                Module::activateModule($module, $cid);
            }

			Output::instance()->resultCode();
	    }else{
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	}
	
	/*
	 * deactivate
	 */
	public function deactivate($cid, $group) {
		$CModule = D("customer_module_group");
		
		$retVal = Session::init();
		if (!retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		//如果当前登陆者是平台管理员或者平台运营管理员则可以进行操作
		$agent = Session::$user['agent'];
		if(Session::isAdmin()||"operate"==$agent){
			$condition["customerId"] = $cid;
			$condition["group"] = $group;
			$condition["permission"] = permission_allow;
			$customerGroup = $CModule->where($condition)->select();
			if ($customerGroup) {
				$where["customerId"] = $cid;
				$where["group"] = $group;
				$CModule->where($where)->setField('permission', permission_deny);

                // 调用模板消息接口, 取消该模块所使用到的模板消息的配置
                $result = R('TemplateMessage/cancelConfigModuleTemplate', [$group, $cid]);
            }

			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	}
	
	
	/*
	 * 激活指定用户的插件
	*/
	public function activeGroupUsage($cid, $groupUsage) {
		$retVal = Session::init();
		if (!retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		//如果当前登陆者是平台管理员或者平台运营管理员则可以进行操作
		$agent = Session::$user['agent'];
		if(Session::isAdmin()||"operate"==$agent){
			Session::switchCustomer(0);
		
			$GModule = D("module_group");
			$where["groupUsage"] = $groupUsage;
			$where["display"] = "1";
			$groups = $GModule->where($where)->select();
			if (!$groups) {
				Output::instance()->resultCode(code_custom_error);
				return;
			}
		
			$CModule = D("customer_module_group");
			foreach ($groups as $group) {
				$condition["customerId"] = $cid;
				$condition["group"] = $group["group"];
				$customerGroup = $CModule->where($condition)->select();
				if (!$customerGroup) {
					$CModule->create();
					$CModule->customerId = $cid;
					$CModule->group = $group["group"];
					$CModule->permission = permission_allow;
					$result = $CModule->add();
				} else {
					$result = $CModule->where($condition)->setField('permission', permission_allow);
				}
				if ($result === FALSE) {
					Log::write($CModule->getLastSql());
					Output::instance()->resultCode(code_sql_error);
					return;
				}
				
				Session::switchCustomer($cid);
				$modules =  $group["modules"];
				$moduleArray = explode(",", $modules);
				foreach ($moduleArray as $module) {
					Module::activateModule($module, $cid);
				}
			}
			
			Output::instance()->resultCode();
		}else {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	}
	
	/*
	 * deactivate
	*/
	public function deactiveGroupUsage($cid, $groupUsage) {
		$GModule = D("module_group");
		$CModule = D("customer_module_group");
		
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		//如果当前登陆者是平台管理员或者平台运营管理员则可以进行操作
		$agent = Session::$user['agent'];
		if(Session::isAdmin()||"operate"==$agent){
			$where["groupUsage"] = $groupUsage;
			$groups = $GModule->where($where)->select();
			if (!$groups) {
				Output::instance()->resultCode(code_custom_error);
				return;
			}
			
			foreach ($groups as $group) {
				$condition["customerId"] = $cid;
				$condition["group"] = $group["group"];
				$condition["permission"] = permission_allow;
				$customerGroup = $CModule->where($condition)->select();
				if ($customerGroup) {
					$where["customerId"] = $cid;
					$where["group"] = $group["group"];
					$CModule->where($where)->setField('permission', permission_deny);
				}
			}
			
			Output::instance()->resultCode();
		}else{
			Output::instance()->resultCode(code_access_denied);
			return;
		}
	}
	
	/*
	 * 显示系统支持的插件
	 */
        public function system($order="id",$orderBy="desc",$start=0,$limit=25) {
		$retVal = Session::init();
		if (!$retVal || !Session::isAdmin()) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$module = D("module");
		$result = $module->order("$order $orderBy")->limit("$start,$limit")->select();
		if (!isset($result)) {
			Output::instance()->resultCode(code_success, "未找到模块");
			return;
		}
		$count = $module->where($where)->count();
// 		Log::write('all module count is:'.$count);
        Output::instance()->objArray($result, $count);
    }

    /*
     * 刷新所有插件和属性
     */
    public function refresh()
    {
        $retVal = Session::init();
        if (!retVal || !Session::isAdmin()) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $moduleModel = D('module_group');

        // 清空数据
        $moduleModel->query('delete from ' . C('DB_PREFIX') . 'group');

        //
        $modules = Module::moduleAll();
        foreach ($modules as $module) {
            $data = Module::moduleData($module);
            if ($data['Name'] == '') {
                continue;
            }

            $moduleModel->create();
            $moduleModel->name = $data['Name'];
            $moduleModel->group = $data['Group'];
            $moduleModel->version = $data['Version'];
            $moduleModel->author = $data['Author'];
            $moduleModel->description = $data['Description'];
            $moduleModel->iconurl = $data['Iconurl'];
            $moduleModel->modules = $data['Modules'];
            $moduleModel->display = $data['Display'];
            $moduleModel->add();
        }

        Output::instance()->resultCode();
    }

    /**
     * 获取角色对应的权限
     *
     * @param string $backend 后台版本号:mp/nmp
     * @param bool $needRuturn 是否函数调用返回到函数(TRUE), 还是输出到页面
     * @return array|void|
     */
	public function getAllRoles($backend = 'mp', $needRuturn = FALSE){
		$retVal = Session::init();
		if (!$retVal) {
			Output::instance()->resultCode(code_access_denied);
			return;
		}
		$agent = Session::$user['agent'];
        $str_agentIds = Session::$user['agentId'];
        $arr_agentIds = explode(',', $str_agentIds);
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
        Session::switchCustomer($customerId);

        if ( Session::isAgent()  ||  (Session::isBusiness() && $backend == 'mp')) {
            // 查询管理员的modules(是管理员的情况下), 和用户常规modules
            $isAdmin = Session::isAdmin();
            $result = $this->getCustomerModuleGroups($customerId, '', $backend);
            $resultAdmin = ($isAdmin) ? $this->getAdminModuleGroups($backend) : [];

            // 合并数据
            $result = (isset($result)) ? $result : [];
            $resultAdmin = (isset($resultAdmin)) ? $resultAdmin : [];
            $result = array_merge($result, $resultAdmin);

        } else {  // 这里是做特殊身份的模块管理(供应商, 仓库)
            $strSql = '';
            if ($backend == 'mp') {
                $strSql = 1;
            } elseif ($backend == 'nmp') {
                $strSql = 2;
            }
			$result = $this->getCustomerModuleGroups($customerId, $strSql, $backend, $arr_agentIds);
		}
		
		if (!isset($result)) {
			Output::instance()->resultCode(code_success, "未找到模块");
			return;
		}
		if ($needRuturn) {
		    return $result;
        } else {
            Output::instance()->objArray($result);
        }

	}
	
	//查询符合条件的用户权限
	private function getCustomerModuleGroups($customerId, $strSql = null, $backend = 'mp' ,$arr_agentIds = []){
	    /** 实例化数据模型 */
        $cuid = Session::$user['id'];
        Session::switchCustomer(0);
        $CModule = D("customer_module_group");
        $moduleGroupModel = D('module_group');
        $roleGroupModel = D('role_module_group');
        $Model_IMI = M('ind_media_info');
        Session::switchCustomer($customerId);

        /**
         * 查询mp版与nmp版module权限数组
         * 注意: $strSql值为1或2都只是为了说明来自特殊身份角色, 没有更特殊含义
         *
         * $backend == mp & $strSql == 1    => mp版特殊身份角色
         * $backend == mp & $strSql == null => mp版agent与business角色获取的权限
         *
         * $backend == nmp & $strSql == 2       => nmp版特殊身份角色
         * $backend == nmp & $strSql == null    => nmp版agent与business角色获取的权限
         */
        if ($backend == 'mp') { // mp版后台, 我实在不知道怎么重构了
            $where['gp.display'] = "1";
            $where['gp.backend'] = $backend;

            // 旧后台做特殊身份的模块管理(供应商, 仓库)
            if ($strSql == 1) {     // 来自特殊身份
                $result = array();
                foreach ($arr_agentIds as $value) {    // 处理角色对应module
                    $where['a.agent'] = $value;
                    $where['a.cid'] = $customerId;

                    $arr = $roleGroupModel
                        ->alias('a')
                        ->where($where)
                        ->join("wx_module_group as gp on a.groupId=gp.id")
                        ->field("gp.id, gp.name, gp.group, gp.description, gp.iconurl, gp.screenIndex,gp.href")
                        ->order("gp.sortOrder asc")
                        ->select();
                    if (empty($arr))
                        continue;

                    $result = array_merge($result, $arr);
                }
            } else {    // 旧后台agent与business角色获取的权限
                $where['customer.customerId'] = $customerId;
                $where['customer.permission'] = permission_allow;

                $result = $CModule
                    ->alias("customer")
                    ->where($where)
                    ->where("gp.backend = '" . $backend . "'")
                    ->join("wx_module_group gp ON customer.group = gp.group")
                    ->field("gp.id, gp.name, gp.group, gp.description, gp.iconurl, gp.screenIndex,gp.href")
                    ->order("gp.sortOrder asc")
                    ->select();
            }

        } elseif ($backend == 'nmp') {  // nmp版后台权限树

            /** 对来自agent与business角色和一般角色的二级module不同处理 */
            if ($strSql == 2) {     // 来自特殊身份
                /** 查询指定授权组 - 角色对应的授权group数组 */
                $where['b.display'] = 1;    // 显示 - 未删除
                $where['b.backend'] = $backend;
                $result = array();
                $authGroups = [];
                foreach ($arr_agentIds as $value) {    // 遍历该人角色
                    $where['a.cid'] = $customerId;
                    $where['agent'] = $value;

                    $arr_group = $roleGroupModel
                        ->alias('a')
                        ->where($where)
                        ->join('wx_module_group as b on a.groupId=b.id')
                        ->getField('group', TRUE);
                    if (empty($arr_group))
                        continue;

                    // 处理二级模块的一级模块
                    $arr_groupPids = $moduleGroupModel
                        ->where(['group' => ['IN', $arr_group], 'display' => 1, 'backend' => 'nmp', 'pid' => ['NEQ', 0], 'beShow' => 1])
                        ->getField('pid', TRUE);
                    if (!empty($arr_groupPids)) {
                        $arr_firstGroup = $moduleGroupModel->where(['id' => ['IN', $arr_groupPids]])->getField('group', TRUE);
                        $arr_firstGroup = !empty($arr_firstGroup) ? $arr_firstGroup : [];

                        $arr_group = array_merge($arr_group, $arr_firstGroup);
                    }

                    $authGroups = array_merge($authGroups, $arr_group);
                }
            }

            /** 查询一级模块列表 */
            $moduleGroupWhere = [
                'backend' => $backend,
                'display' => 1,
                'pid' => 0
            ];
            if ($strSql == 2) { // 特殊身份查询一级模块, 需要时角色对应的
                $moduleGroupWhere['group'] = ['IN', $authGroups];
            }

            $firstLevelModules = $moduleGroupModel
                ->where($moduleGroupWhere)
                ->order("sortOrder asc")
                ->field('id, name, group, description, iconurl, modules, groupUsage, href, pid')
                ->select();

            /** 查询二级模块 */
            if ($strSql == 2) {     // 来自特殊身份

                // 这里传TRUE是因为普通用户, 二级模块需要鉴权, 且指定role对应的group授权数组
                $result = $this->getSecondLevels($firstLevelModules, 'sortOrder', 'asc', TRUE, $authGroups);
            } else {    // nmp版agent与business角色获取的权限

                // 这里传TRUE是因为普通用户, 二级模块需要鉴权
                $result = $this->getSecondLevels($firstLevelModules, 'sortOrder', 'asc', TRUE);
            }
        }

        /** 返回 */
        return $result;
    }

    /**
     * 查询管理员权限
     *
     * @param string $backend 后台版本号
     * @return                  管理员权限目录数组
     */
    private function getAdminModuleGroups($backend = 'mp')
    {
        $customerId = Session::$user['customerId'];
        Session::switchCustomer(0);
        $Module = D("module_group");
        Session::switchCustomer($customerId);

        // 筛选管理员权限目录条件
        $where['display'] = '1';
        $where['backend'] = $backend;
        if ($backend == 'mp') {  // mp版后台超管模块
            $where['groupUsage'] = '平台管理';
            $field = "id, name, group, description, iconurl, groupUsage, screenIndex, href";
            $order = "sortOrder asc";
        } elseif ($backend == 'nmp') {   // nmp版后台超管模块
            $where['pid'] = -1;         // pid:-1 - 超管模块(同时也是一级模块)/0-一级模块
            $field = "id, name, group, description, iconurl, modules, groupUsage, href, pid";
            $order = "id asc";
        }

        // 查询管理员一级导航目录
        $result = $Module->where($where)->field($field)->order($order)->select();

        // 相对mp版而言, 只有nmp版才需要做子级目录拼接
        if ($backend == 'nmp') {
            // 这里传false是因为超级管理员二级模块也不需要鉴权
            $result = $this->getSecondLevels($result, 'id', 'asc', FALSE);
        }

        return $result;
    }

    /**
     * 根据一级导航栏目查询其下属的二级栏目
     * nmp版新增
     *
     * @param array $firstLevelModules 一级导航栏目
     * @param string $order 排序规则
     * @param string $orderBy
     * @param bool $showAuth 是否需要开启module鉴权
     * @return mixed                    返回组装好包含二级导航栏目的一级整体栏目数组
     */
    private function getSecondLevels($firstLevelModules, $order = "id", $orderBy = "asc", $shouldAuth = FALSE, $authGroups = [])
    {
        $customerId = Session::$user['customerId']; // 鉴权, 获得登录用户的customerId, 去表wx_customer_module_group中查找授权信息
        $cuid = Session::$user['id'];
        Session::switchCustomer(0);
        $ModuleGroup = D("module_group");
        $customerModuleModel = D('customer_module_group');
        $Model_IMI = M('ind_media_info');
        Session::switchCustomer($customerId);

        if ($shouldAuth) {  // 如果需要鉴权, 查询用户授权的groups数组
            if (empty($authGroups)) {   // 没传入授权组
                $customerModuleWhere = ['customerId' => $customerId, 'permission' => permission_allow];
                $groups = $customerModuleModel->where($customerModuleWhere)->getField('group', true);
            } else {                    // 传入指定授权组
                $groups = $authGroups;
            }
            $groups = !empty($groups) ? $groups : [];
        }

        // 特殊权限 - 审核人
        $arr_reviewer = $Model_IMI->where(['deleted' => 0, 'ifReview' => 1])->getField('reviewer', TRUE);   // 查询自媒体账号的审核者
        if (in_array($cuid, $arr_reviewer)) {   // 如果这个人是审核者的话, 对他开发审核模块
            array_push($groups, 'audit'); // 审核模块
        }

        // 如果不是超级管理员, 且该用户没有权限, 则直接返回[]
        if (!Session::isAdmin() && empty($groups)) {
            return [];
        }
        // 遍历一级菜单树, 查询各个一级菜单树下的二级菜单树信息
        foreach ($firstLevelModules as $first_index => $firstLevelModule) {
            $where['pid'] = $firstLevelModule['id'];
            if ($shouldAuth) {  // 如果需要鉴权的, 则加上筛选条件, 筛选用户有权限的groups数组, 否则仅筛选一级菜单下的全部子级即可
                $where['group'] = array('in', $groups);
            }
            // 查询二级菜单树
            $secondLevelModules = $ModuleGroup
                ->where($where)
                // ->join('wx_role_module_group as b on a.id=b.groupId')
                ->order("$order $orderBy")
                ->field('id, name, group, description, iconurl, modules, groupUsage, href, pid, beShow')
                ->select();

            $secondCount = $ModuleGroup->where(['pid' => $firstLevelModule['id']])->count();
            // 如果包含子级模块, 并且子级模块都没有权限, 那么一级模块也不显示
            if ($shouldAuth && ($secondCount > 0) && (count($secondLevelModules) == 0)) {
                unset($firstLevelModules[$first_index]);
                continue;
            }
            // 根据二级导航栏目数据修改其一级导航栏目相关数据
            $firstLevelModules[$first_index]['childs'] = $secondLevelModules ? $secondLevelModules : [];
        }
        return $firstLevelModules;
    }
	
}